// 基础配置
const config = {
  baseURL: 'http://192.168.31.36:9002', 
  // baseURL: 'http://43.138.23.97:9001',// 修改为Nginx配置的域名
  timeout: 90000, // 超时时间
  header: {
    'Content-Type': 'application/json'
  }
}

// 请求队列
let requestQueue = []
// 是否正在刷新token
let isRefreshing = false
// 重试队列
let retryQueue = []

// 请求拦截器
const requestInterceptor = (options) => {
  // 获取token
  const token = uni.getStorageSync('token')
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `Bearer ${token}`
    }
  }
  return options
}

// 响应拦截器
const responseInterceptor = (response) => {
  const { statusCode, data } = response
  
  // 请求成功
  if (statusCode >= 200 && statusCode < 300) {
    return data
  }
  
  // 处理特定错误码
  switch (statusCode) {
    case 401:
      // token过期，尝试刷新token
      return handleTokenExpired(response)
    case 403:
      uni.showToast({
        title: '没有权限访问',
        icon: 'none'
      })
      return Promise.reject(new Error('没有权限访问'))
    case 404:
      uni.showToast({
        title: '请求的资源不存在',
        icon: 'none'
      })
      return Promise.reject(new Error('请求的资源不存在'))
    case 500:
      uni.showToast({
        title: '服务器错误',
        icon: 'none'
      })
      return Promise.reject(new Error('服务器错误'))
    default:
      uni.showToast({
        title: data.message || '请求失败',
        icon: 'none'
      })
      return Promise.reject(new Error(data.message || '请求失败'))
  }
}

// 处理token过期
const handleTokenExpired = async (response) => {
  if (isRefreshing) {
    // 如果正在刷新token，将请求加入队列
    return new Promise((resolve, reject) => {
      retryQueue.push({ resolve, reject })
    })
  }
  
  isRefreshing = true
  
  try {
    // 获取refreshToken
    const refreshToken = uni.getStorageSync('refreshToken')
    if (!refreshToken) {
      throw new Error('未找到refreshToken')
    }
    
    // 刷新token
    const res = await uni.request({
      url: `${config.baseURL}/auth/refresh`,
      method: 'POST',
      header: {
        'Authorization': `Bearer ${refreshToken}`
      }
    })
    
    if (res.statusCode === 200) {
      const { access_token, refresh_token } = res.data.data
      // 保存新token
      uni.setStorageSync('token', access_token)
      uni.setStorageSync('refreshToken', refresh_token)
      
      // 重试队列中的请求
      retryQueue.forEach(({ resolve, reject }) => {
        resolve()
      })
      retryQueue = []
      
      // 重试当前请求
      const options = responseInterceptor(response)
      return request(options)
    } else {
      throw new Error('刷新token失败')
    }
  } catch (error) {
    // 刷新token失败，清除token并跳转到登录页
    uni.removeStorageSync('token')
    uni.removeStorageSync('refreshToken')
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return Promise.reject(error)
  } finally {
    isRefreshing = false
  }
}

// 请求重试
const retry = (options, retryCount = 0) => {
  const maxRetries = 3
  if (retryCount >= maxRetries) {
    return Promise.reject(new Error('请求重试次数过多'))
  }
  
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      request(options)
        .then(resolve)
        .catch(() => {
          retry(options, retryCount + 1)
            .then(resolve)
            .catch(reject)
        })
    }, 1000 * (retryCount + 1))
  })
}

// 统一请求方法
const request = (options) => {
  // 合并配置
  options = {
    ...config,
    ...options,
    url: `${config.baseURL}${options.url}`
  }
  
  // 请求拦截
  options = requestInterceptor(options)
  
  // 发起请求
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      success: (res) => {
        resolve(responseInterceptor(res))
      },
      fail: (err) => {
        // 网络错误等，进行重试
        retry(options)
          .then(resolve)
          .catch(reject)
      }
    })
  })
}

// 导出请求方法
export const http = {
  get: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'GET',
      ...options
    })
  },
  
  post: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'POST',
      ...options
    })
  },
  
  put: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'PUT',
      ...options
    })
  },
  
  delete: (url, data = {}, options = {}) => {
    return request({
      url,
      data,
      method: 'DELETE',
      ...options
    })
  }
}

// 导出默认配置
export default config
